package com.bw.house.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {

    public static List<Map> readExcel(String ext, InputStream inputStream) throws IOException {//读取excel工具类
        List<Map> list=new ArrayList();

        Workbook wb=null;
        if(".xls".equals(ext)){
            wb= new HSSFWorkbook(inputStream);
        }
        if(".xlsx".equals(ext)){
            wb= new XSSFWorkbook(inputStream);
        }

        Sheet sheet=wb.getSheetAt(0);//获取第一个sheet页
        int rowNum = sheet.getLastRowNum();//获取数据行号
        for(int i=2;i<=rowNum;i++){
            Row row=sheet.getRow(i);//读取某一行的数据

            Map map=new HashMap();
            int cellNum = row.getLastCellNum();//获取列的个数
            for(int j=0;j<cellNum;j++){
                String key=getKey(sheet.getRow(1).getCell(j));//获取第二行每一列的数据
                Object value=getValue(row.getCell(j));//获取当前行每一列的数据
                map.put(key,value);
            }
            list.add(map);
        }
        return list;
    }

    public static String getKey(Cell cell){
        return cell.getStringCellValue();
    }
    public static Object getValue(Cell cell){
        if(null==cell){
            return null;
        }


        int cellType = cell.getCellType();//获取单元格数据的格式

        Object value=null;
        switch (cellType){
            case Cell.CELL_TYPE_STRING:
                value=cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value=null;
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value=cell.getBooleanCellValue();
            case Cell.CELL_TYPE_NUMERIC:
                if(DateUtil.isCellDateFormatted(cell)){
                    value=cell.getDateCellValue();
                }else{
                    value=cell.getNumericCellValue();
                }
                break;
        }

        return value;
    }
}
